<template>
  <el-dialog :modelValue="show" title="后台账号" :close-on-click-modal="false" :close-on-press-escape="false" top="20vh"
    @close="handleClose">
    <el-form :model="data.addQuery" ref="addQuery" :validate-on-rule-change="false" :rules="data.rules" :scroll-to-error="true">
      <form-item title="账号昵称" :pass="true" value="nickname">
        <el-input type="text" v-model="data.addQuery.nickname" placeholder="请输入账号昵称" clearable maxlength="20" />
        <span class="tipsText">(后台账号的描述昵称)</span>
      </form-item>
      <form-item title="后台账号" :pass="true" value="username">
        <el-input type="text" v-model="data.addQuery.username" placeholder="请输入后台账号" clearable maxlength="20"
          :disabled="data.addQuery.id ? true : false" />
          <span class="tipsText">(后台登录账号)</span>
      </form-item>
      <form-item title="账号密码" :pass="data.rules.password[0].required" value="password">
        <el-input type="text" v-model="data.addQuery.password" placeholder="请输入账号密码" clearable maxlength="20" />
        <span class="tipsText">(后台登录账号密码)</span>
      </form-item>
      <form-item title="账号角色" :pass="true" value="role_id">
        <el-select v-model="data.addQuery.role_id" filterable placeholder="请选择账号角色" clearable>
          <el-option v-for="(item, index) in data.roleList" :key="item.id" :label="item.role_name" :value="item.id" />
        </el-select>
        <span class="tipsText">(该账号所属的角色权限)</span>
      </form-item>
      <form-item title="锁定" value="status">
        <el-radio-group v-model="data.addQuery.status" size="large">
          <el-radio-button :label="item.label" v-for="item in LOCKSTATUS" :key="item.value" :value="item.value" />
        </el-radio-group>
        <span class="tipsText">(锁定后该账号无法登录后台)</span>
      </form-item>
      <form-item title="是否验证谷歌验证码" value="google_check">
        <el-radio-group v-model="data.addQuery.google_check" size="large" @change="chooseGoogle">
          <el-radio-button label="不验证" :value="0" />
          <el-radio-button label="验证" :value="1" />
        </el-radio-group>
        <span class="tipsText">(开启谷歌验证后，登录后台需输入谷歌验证码；首次开启此功能需进行绑定“身份验证器”)</span>
      </form-item>
      <form-item title="谷歌Url" value="google_url" v-show="data.addQuery.google_check" style="height:auto">
        <QrcodeVue :value="data.addQuery.google_url" :size="140" fg-color="#000" />
        <el-input class="marginT5" v-model="data.addQuery.google_url" type="text" readonly />
        <span class="tipsText">(该账号绑定的谷歌Url，自动生成)</span>
      </form-item>
      <form-item title="谷歌秘钥" value="google_secret" v-show="data.addQuery.google_check">
        <el-input class="marginT5" v-model="data.addQuery.google_secret" type="text" readonly />
        <span class="tipsText">(该账号绑定的谷歌秘钥，自动生成)</span>
      </form-item>
      <form-item title="谷歌验证码" :pass="props.checkedItem.google_check || data.addQuery.google_check ? true : false" value="google_code"
        v-show="props.checkedItem.google_check || data.addQuery.google_check">
        <el-input class="marginT5" v-model="data.addQuery.google_code" type="text" placeholder="请输入谷歌验证码" />
        <span class="tipsText">(该账号绑定的谷歌验证码)</span>
      </form-item>
      <form-item title="白名单IP" value="white_ip">
        <el-input type="textarea" rows="3" v-model="data.addQuery.white_ip" placeholder="请输入白名单IP,多个IP用( ; )分开" clearable />
        <span class="tipsText">(该账号只能在设定的IP地址下登录才能进入后台)</span>
      </form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, watch, onMounted } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import QrcodeVue from 'qrcode.vue'
import { LOCKSTATUS } from '@/config/eunm'
import { systemChangeManager, systemAddManager, systemRoleList } from '@/api/user'
import { googleKey } from '@/api/merchant'
import FormItem from '@/components/FormItem/FormItem.vue'
const props = defineProps({
  show: {
    type: Boolean,
    default: () => {
      return false
    }
  },
  checkedItem: {
    type: Object,
    default: () => {
      return {}
    }
  }
})

const addQuery = ref<FormInstance>()

watch(
  () => props.checkedItem,
  async (val) => {
    if (val.id) {
      data.addQuery = Object.assign(data.addQuery, props.checkedItem)
      data.rules.password[0].required = false
    } else {
      data.rules.password[0].required = true
      addQuery.value?.resetFields()
      data.addQuery = {
        id: 0,
        username: '',
        password: '',
        nickname: '',
        role_id: '',
        status: 1,
        white_ip: '',
        google_check: 0, // IP白名单
        google_url: '', // 谷歌二维码
        google_secret: '', // 谷歌二维码
        google_code: '', // 谷歌验证码
      }
    }
  }
)

interface roleType {
  id: number
  role_name: string
  permissions: string
  status: number
  createAt: string
}
const data = reactive({
  addQuery: {
    id: 0,
    username: '',
    password: '',
    nickname: '',
    role_id: '',
    status: 0,
    white_ip: '',
    google_check: 0, // IP白名单
    google_url: '', // 谷歌二维码
    google_secret: '', // 谷歌二维码
    google_code: '', // 谷歌验证码
  },
  rules: {
    nickname: [{ required: true, message: '请输入', trigger: 'blur' }],
    username: [{ required: true, message: '请输入', trigger: 'blur' }],
    password: [
      { required: true, message: '请输入', trigger: 'blur' },
      { min: 6, max: 20, message: '请输入6-20位字符', trigger: 'blur' }
    ],
    // white_ip: [{ required: true, message: '请输入', trigger: 'blur' }],
    role_id: [{ required: true, message: '请选择', trigger: 'change' }],
    status: [{ required: true, message: '请选择', trigger: 'change' }],
    google_check: [{ required: true, message: '请选择', trigger: 'change' }]
  },
  roleList: [] as roleType[]
})

onMounted(async () => {
  const roleList = await systemRoleList({ role_name: '', page: 1, size: 999 })
  data.roleList = roleList.data.list
})

const save = async () => {
  await addQuery.value?.validate(async (valid: any, fields: any) => {
    if (valid) {
      let query = JSON.parse(JSON.stringify(data.addQuery))
      if(props.checkedItem.google_check && !query.google_code){
        return ElMessage({ message: '请输入谷歌验证码', type: 'error' })
      }else if(!props.checkedItem.google_check && !query.google_check){
        query.google_code = 0
        query.google_url = ''
        query.google_secret = ''
      }else if(query.google_check && !query.google_code){
        return ElMessage({ message: '请输入谷歌验证码', type: 'error' })
      }else if(query.google_code){
        query.google_code = Number(query.google_code)
      }
      const res: any = query.id ? await systemChangeManager(query) : await systemAddManager(query)
      if (res.code == 1) {
        ElMessage({ message: '操作成功', type: 'success' })
      }
      emit('onHideDetails', true)
    }
  })
}

// 是否开启谷歌验证码
const chooseGoogle = async (val: number) => {
  if (val) {
    if (!data.addQuery.username) {
      data.addQuery.google_check = 0
      return ElMessage({
        type: 'error',
        message: '请输入用户昵称'
      })
    } else {
      if(data.addQuery.google_url) return 
      let res = await googleKey({ username: data.addQuery.username })
      data.addQuery.google_url = res.data.google_url
      data.addQuery.google_secret = res.data.google_secret
    }
  }
}

// 取消
const emit = defineEmits(['onHideDetails'])
const handleClose = async () => {
  emit('onHideDetails', false)
}
</script>

<style lang="scss" scoped></style>
